class MgTeacherCard {
    constructor() {

        this.tableFilter = "filter-body-teacher-details-table";
        this.tableId = "id-body-teacher-details-table";

        var load = this;
        this.rootPath = "http://localhost:8090/manage-sys";
        this.idCardPath = "manage-system-backed-idCard";

        this.idCard = localStorage.getItem(this.idCardPath);

        this.dataRank = [60,70,80,90,100];

        this.echartsIdSuffix = '-echarts';

        // 绘制教师详情页可视化的myEcharts对象
        this.pieEcharts = new MyECharts();

        this.teacherDetailsTableSet = {
            elem: '#'
            , defaultToolbar: ['filter', 'print', 'exports']
            // , height: 312
            , url: '/Lock/GetCouEle' //数据接口
            , where: { idCard: this.idCard }
            , page: true //开启分页
            , toolbar: '#barDemo'
            , cols: [[ //表头
                { field: 'id', title: 'ID', width: '10%', sort: true }
                , { field: 'sname', title: '姓名', width: '10%' }
                , { field: 'ssex', title: '性别', width: '10%', sort: true }
                , { field: 'sage', title: '年龄', width: '10%', sort: true }
                , { field: 'cscore', title: '分数', width: '10%', edit: "text", sort: true }
                , {
                    field: 'isPass', title: '是否及格',
                    templet: function (d) {
                        if (d.cscore) {
                            if (d.cscore >= 60) return "及格";
                            else return "不及格";
                        } else {
                            return "";
                        }
                    }
                    , width: '20%', sort: true
                }
                , {
                    field: 'edit', title: '编辑确认',
                    templet: "#tool-tab-col-exit"
                    , width: '10%', sort: true, align: "center"
                }
            ]]
            , contentType: 'jsonp'//一定要是jsonp类型
            , parseData: function (res) { //res 即为原始返回的数据

                // console.log(res.status)
                console.log(res);
                var arry = [];
                var list = res.list;
                for (let i = 0; i < list.length; i++) {
                    let e = list[i];
                    arry[i] = ({
                        'id': e.sid
                        , 'sname': e.stud.sname
                        , 'ssex': (e.stud.ssex ? '男' : '女')
                        , 'sage': e.stud.sage
                        , 'cscore': e.cscore
                    });
                }
                console.log(arry);

                return {
                    "code": res.statue, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": arry.length, //解析数据长度
                    "data": arry //解析数据列表
                };
            }
            , request: {
                pageName: 'pageInd' //页码的参数名称，默认：page
                , limitName: 'rowCount' //每页数据量的参数名，默认：limit
            }
            ,done: function(resp){
                console.log("resp");
                console.log(resp);
                var data = resp.data;
                var chartsData=[];

                let temp={"不及格":0,"60-69":0,"70-79":0,"80-89":0,"90-99":0,"满分":0};

                for(let i=0;i<data.length;i++){
                    if(data[i].cscore<60) temp["不及格"]++;
                    else if(data[i].cscore<70)  temp["60-69"]++;
                    else if(data[i].cscore<80)  temp["70-79"]++;
                    else if(data[i].cscore<90)  temp["80-89"]++;
                    else if(data[i].cscore<100) temp["90-99"]++;
                    else if(data[i].cscore==100)    temp["满分"]++;
                }

                for(let e in temp){
                    chartsData.push({"value": temp[e],"name":e});
                }

                let obj=load.pieEcharts.getdefaultOption();
                obj.series[0]["data"]=chartsData;

                console.log(obj);

                console.log("----------------------");
                load.pieEcharts.setDate(obj);

                console.log(chartsData);

                
            }
        }
    }

    startCard() {

        var load = this;
        // 绑定点击了教师卡片后发送的事情
        $(".admin-mg-teacher-card").on("click", function (e) {
            console.log("admin-mg-teacher-card");
            // console.log($(".layui-body-teacher-details").siblings());
            $(".layui-body-teacher-details").show().siblings().hide();

            // 教师号
            let aid = this.tid;

            // 渲染教师任教课程的折叠面板
            $.get("/Lock/GetTeaCourse", { tid: aid }, function (resp) {
                console.log("teacher-cared");
                
                load.renderteacherDetailsCollapseItem(resp);
            });

        })


    }

    // 渲染教师详情页的折叠面板项
    renderteacherDetailsCollapseItem(resp) {
        console.log("------------------ renderteacherDetailsCollapseItem start -----------------");

        var load = this;

        var courses = resp.courseList;

        console.log(courses);

        var htmlstr = "";



        for (let i = 0; i < courses.length; i++) {

            htmlstr += template("template-teacher-details-card-body-collapse-item", courses[i]);

        }

        $(".teacher-details-card-body .layui-collapse").html(htmlstr);

        layui.use('element', function () {
            var element = layui.element;
            element.render('collapse');
        });

        //   为每一个折叠项设置两个自定义属性，一个为对应的课程号，一个为其中表格的id号
        for (let i = 0; i < courses.length; i++) {
            let tableId = courses[i].tid + "-" + courses[i].cid;
            $(".teacher-details-card-body .layui-colla-item")[i].setAttribute('cid', courses[i].cid);
            $(".teacher-details-card-body .layui-colla-item")[i].setAttribute('table-id', tableId);
            $(".teacher-details-card-body .layui-colla-item table")[i].id = tableId;
            $(".teacher-details-card-body .sub-echerts")[i].id = tableId + this.echartsIdSuffix;
        }

        $(".teacher-details-card-body .sub-echerts").hide();



        $(".teacher-details-card-body .layui-colla-item").attr('flag', 1);


        $(".teacher-details-card-body .layui-colla-item").on('click', function () {

            var thisLoad = this;

            if ($(this).attr('flag') != '1') {
                return;
            }

            $(this).attr('flag', 0);


            layui.use('table', function () {

                load.teacherDetailsTableSet.where.cid = $(thisLoad).attr('cid');


                load.teacherDetailsTableSet.elem = '#' + $(thisLoad).attr('table-id');

                var table = layui.table;

                table.render(load.teacherDetailsTableSet);

                //触发事件
                table.on('toolbar('+load.tableFilter+')', function (obj) {
                    console.log("toolbar-test");
                    var chartId = obj.config.id + load.echartsIdSuffix;
                    var dom = document.getElementById(chartId)
                    // var checkStatus = table.checkStatus(obj.config.id);//获取选中的行
                    switch (obj.event) {
                        case 'visualize':
                            // console.log(this);

                            if (dom.getAttribute("isRender")) $("#" + chartId).slideToggle();
                            else {
                                $("#" + chartId).attr('isRender',true).toggle();
                                
                            }
                            load.pieEcharts.renderCharts(dom);

                            break;
                    };
                });

            });

        })//点击事件右括号

        this.addEvent();

        console.log("------------------ renderteacherDetailsCollapseItem end -----------------");
    }


    addEvent(){

        let load = this;

        let table = layui.table;

        let form = layui.form;

        table.on('tool('+load.tableFilter+')', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"

            var layEvent = obj.event;
            var data = obj.data;

            var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）


            var btnLoad = this;


            if (layEvent === 'edit') { //编辑
                console.log("edit-------------------------");

                // 即在禁用状态点击其效果无效
                if ($(btnLoad).prop("class").indexOf(MyUtils.tableBtnDistabled) != -1) {
                    console.log("disabled");
                    return;
                }

                let editLoad = this;


                layer.confirm('确认修改？', { icon: 3, title: '提示' }, function (index) {
                    $(btnLoad).addClass("layui-btn-disabled");

                    layer.close(index);//关闭弹出层


                    console.log(data);
                    let sid = data['id'];
                    let cscore = data['cscore'];
                    // console.log($(btnLoad).parents('.layui-colla-item'));
                    let cid = $(btnLoad).parents('.layui-colla-item').eq(0).attr('cid');

                    console.log(sid);
                    console.log(cid);
                    console.log(cscore);


                    
                    
                    // 对后端发出更新请求
                    $.ajaxSetup({ contentType: "application/json; charset=utf-8" });
                    $.get("/Lock/Update/Ele/Score", { 'sid' :sid,'cid':cid,'cscore':cscore}, function (resp) {
                        if (resp.statue == 0) {
                            layer.msg(resp.message, { icon: 6 });
                            table.render();
                        } else {
                            layer.msg(resp.message, { icon: 5 });
                        }

                        table.render(load.teacherDetailsTableSet);
                    })

                });


            }
        });


        table.on('edit('+load.tableFilter+')', function (obj) { //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
            
            console.log("edit");
            // console.log(this);
            MyUtils.startEditBtn(this);

        });


        form.on("select", function () {
            MyUtils.startEditBtn(this);
        });


        //触发事件
        table.on('toolbar('+load.tableFilter+')', function (obj) {

            console.log("toolbar");
            var id =(obj.config.id);                   
            switch (obj.event) {
                case 'add':
                    load.addLayerindex=layer.open({
                        type: 1,
                        shade: 0,
                        content: $('#id-body-stud-tab-table-add'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                      });
                    
                    
                    // layer.msg('添加');
                    break;
            };
        });
    }


}